/*******************************************************************************
 *    版权信息   ： @copyright Copyright 2014-2021 chnenergy All Right Reserved
 *    作   者   ： hhz
 *    版   本   ： 1.1
 *    创建时间   ：2024/4/16
 *    最后修改日期   ： 2024/4/16
 *    最后修改人员   ： hhz
 ******************************************************************************/
package io.github.houhanzhi.hhregistry.health;

import io.github.houhanzhi.hhregistry.model.InstanceMeta;
import io.github.houhanzhi.hhregistry.service.HHRegistryService;
import io.github.houhanzhi.hhregistry.service.RegistryService;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 探活
 **/
@Slf4j
public class HHHealthChecker implements HealthChecker {

    RegistryService registryService;

    public HHHealthChecker(RegistryService registryService) {
        this.registryService = registryService;
    }

    final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

    // 心跳间隔超时时间
    long timeout = 20_000;

    @Override
    public void start() {
        executorService.scheduleWithFixedDelay(
                () -> {
                    log.info(" ===> Health checker running...");
                    long now  = System.currentTimeMillis();
                    HHRegistryService.TIMESTAMPS.keySet().stream().forEach(serviceAndInst -> {
                        final Long timestamp = HHRegistryService.TIMESTAMPS.get(serviceAndInst);
                        if (now -  timestamp > timeout) {
                            log.info(" ===> Health checker: {} is down", serviceAndInst);
                            int index = serviceAndInst.indexOf("@");
                            final String service = serviceAndInst.substring(0, index);
                            final String url = serviceAndInst.substring(index + 1);
                            InstanceMeta instance = InstanceMeta.from(url);
                            registryService.unregister(service, instance);
                            HHRegistryService.TIMESTAMPS.remove(serviceAndInst);
                        }
                    });

                },
                10, 10, TimeUnit.SECONDS);
    }

    @Override
    public void stop() {
        executorService.shutdown();
    }
}
